'''
Created on January 11, 2010

'''

import subprocess
from os import popen

class ServiceHandler(object) :
    '''manage system services like start , stop , disable and restart '''
    
    def __init__(self) :
        pass

    def getServices(self):
        '''get all services on the system'''
        serviceCall = popen("ls /etc/init.d/")
        services = serviceCall.read()
        serviceCall.close()
        
        services = services.strip().split("\n")
        return services
    
    def start (self, serviceName) :
        '''start service'''
        
        if subprocess.call("/etc/init.d/" + serviceName + " start > /dev/null 2>&1", shell= True): 
            return False
        
        else:
            return True
    
    
    def stop (self, serviceName) :
        '''stop service'''
        
        if subprocess.call("/etc/init.d/" + serviceName + " stop > /dev/null 2>&1", shell = True): 
            return False
        
        else:
            return True
    
    
    def restart (self, serviceName) :
        '''restart service'''
        
        if subprocess.call("/etc/init.d/" + serviceName + " restart > /dev/null 2>&1", shell = True) :
            return False
        
        else :
            return True
    
    
    
    def status (self, serviceName) :
        '''service status'''
        
        serviceStatus = popen("/etc/init.d/" + serviceName + " status 2> /dev/null").read()
        
        if serviceStatus :
            return serviceStatus
        else :
            return False

def main():
    # THE FOLLOWING CODE IS JUST FOR TESTING
    # CODER DISCRITION IS ADVISED :D
    
    from time import sleep 
    
    x = ServiceHandler()
    
    if x.start("smb") :
        print "service started successfully"
    
    else :
        print "Failed to start the service"
    
    sleep(3)
    if x.stop("smb"):
        print "service is stopped"
    
    else :
        print "Failed to stop the service"
    
    sleep(3)
    if x.restart("smb") :
        print "service restarted"
    
    else :
        print "Failed to restart the service"
    
    sleep(3)
    output =  x.status("ssh")
    
    if output:
        print "Got status:-\n", output
    
    else :
        print "Failed to get status"
    

if __name__ == "__main__" :
    # Call the main function here to test this module
    main()
    #pass
    